/**
 * @description: 文件上传服务
 *
 */

import { Injectable } from '@nestjs/common';
import { extname, join } from 'node:path';
import { existsSync, mkdirSync } from 'node:fs';
import { diskStorage } from 'multer';

@Injectable()
export class MulterStorageService {
  private uploadPath = join(__dirname, '../../../uploads');

  constructor() {
    if (!existsSync(this.uploadPath)) {
      mkdirSync(this.uploadPath, { recursive: true });
    }
  }


  getStorageEngine() {
    return diskStorage({
      destination: (req, file, cb) => {
        console.log('文件上传路径', this.uploadPath);
        cb(null, this.uploadPath); // 保存上传文件的目标文件夹
      },
      filename: (req, file, cb) => {
        // 生成唯一文件名，避免文件重名
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
        const ext = extname(file.originalname);
        const filename = `${file.fieldname}-${uniqueSuffix}${ext}`;
        cb(null, filename);
      },
    });
  }

  getUploadPath() {
    return this.uploadPath;
  }
}
